#!/bin/python #encoding=utf-8
def encode_multipart_formdata(fields,files = []):
    """
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files.
    Return (content_type, body) ready for httplib.HTTPConnection instance
    """
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_---$---'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body

from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.is_login = True
        

    def handle_starttag(self, tag, attrs):
        if tag == 'form' :
            if len(attrs) > 0 and attrs[0] == ('action','account.php'):
                self.is_login = False



import urllib2,cookielib,urllib,time

def do_autocommit(data):
    ck = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(ck))
    h = opener.open("http://www.easyarticles.com/account.php")
    parser = MyHTMLParser()
    parser.feed(h.read())
    while parser.is_login == False:
        parser.reset()
        parser.is_login = True
        h.close()
        param = urllib.urlencode({'user':'test1983','password':'wwwwwwwwww','submit':'Submit'})
        h.close()
        h = opener.open("http://www.easyarticles.com/account.php",param)
        parser.feed(h.read())
        time.sleep(1);
    
    
    urllib2.install_opener(opener)
    fields = [('subject',data['subject']),('titletext','title'),('maintext',data['text']),('authortext',data['author']),('catid','1'),('preview','Preview')]
    content_type, body = encode_multipart_formdata(fields)
    headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
    r = urllib2.Request('http://www.easyarticles.com/account.php?action=post2', body, headers)
    try:
        h = urllib2.urlopen(r)
    except urllib2.URLError:
        return ''
    
    return h.read()

if __name__ == '__main__':
    f = open('easy.html','w')
    f.write(do_autocommit({'subject':'test','text':'ok','author':'ft'}))
    f.close()
